<template>
  <div class="fillcontain">
    <head-top></head-top>
  
    <div class="table_container">
  
      <el-radio-group v-model="timeType" @change="onTypeChange">
        <el-radio-button label="未来排课"></el-radio-button>
        <el-radio-button label="过往排课"></el-radio-button>
      </el-radio-group>
      <div style="float:right">
        <el-date-picker v-model="timeArrange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
        <el-button type="primary" icon="el-icon-search" style="margin-left:10px" @click="searchByTimeArrange">搜索</el-button>
      </div>
      <div style="margin-top:8px">
        <el-button :type="isBatchManage?'info':'primary'" @click="batchManage">{{isBatchManage?'取消':'批量管理'}}</el-button>
        <el-button v-if="isBatchManage" type="danger" @click="deleteSelectedArrange">删除选中</el-button>
        <div style="float:right">
          <el-autocomplete v-model="filterUser" :fetch-suggestions="querySearchAsync" placeholder="老师或学生姓名进行筛选" style="width: 250px;margin-left:40px" @select="addressSelect"></el-autocomplete>
          <el-button type="primary" icon="el-icon-delete" @click="removeFilter" style="margin-left:10px">清空筛选</el-button>
        </div>
      </div>
      <el-table ref="multipleTable" style="margin-top:10px" :data="tableData" border :default-sort="{prop: 'date', order: 'ascending'}" stripe @sort-change='sortChange' @selection-change="handleSelectionChange">
        <el-table-column v-if="isBatchManage" type="selection"></el-table-column>
        <el-table-column prop="date" label="日期" sortable='custom' width="180">
        </el-table-column>
        <el-table-column prop="teacher_name" label="老师" sortable='custom' width="180">
        </el-table-column>
        <el-table-column prop="student_name" label="学生" sortable='custom' width="180">
        </el-table-column>
        <el-table-column prop="status_str" label="状态" sortable='custom' width="180">
        </el-table-column>
        <el-table-column prop="clocked_str" label="是否已打卡" width="180">
        </el-table-column>
        <el-table-column prop="time_from" label="开始时间" width="180">
        </el-table-column>
        <el-table-column prop="time_to" label="结束时间" width="180">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template scope="scope">
          <el-button type="text" @click="handleClick(scope.row)" size="small">修改</el-button>
        <el-button type="text" @click="handleDeleteClick(scope.row)" size="small">删除</el-button>
        <!-- <el-button  v-if="scope.row.status!=0" type="text" @click="confirmUser(scope.row)" size="small">确认</el-button> -->
</template>
   			 </el-table-column>
			</el-table>
			<div class="Pagination" style="text-align: left;margin-top: 10px;">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-size="50" layout="total, prev, pager, next" :total="count">
        </el-pagination>
      </div>
		</div>

    <el-dialog title="是否确认删除以下排课？" :visible.sync="dialogDeleteConfirm">
  <el-table :data="multipleSelection"  stripe   height="250">
     <el-table-column prop="date" label="日期" width="180">
        </el-table-column>
        <el-table-column prop="teacher_name" label="老师"  width="180">
        </el-table-column>
        <el-table-column prop="student_name" label="学生"  width="150">
        </el-table-column>
          <el-table-column prop="time_from" label="开始时间" width="150">
        </el-table-column>
        <el-table-column prop="time_to" label="结束时间" width="150">
        </el-table-column>
  </el-table>
  <div style="display:flex;flex-direction:row;aligin-items:center;justify-content:center;margin-top:20px">
        <el-button type="info" @click="dialogDeleteConfirm = false">取 消</el-button>
        <el-button style="margin-left:50px"  type="danger" @click="deleteArrange">确认删除</el-button>
      </div>
</el-dialog>

		  <el-dialog v-loading="changeLoading" title="修改排课信息" :visible.sync="dialogChangeVisible">
			   <el-row style="margin-top: 20px;">
      <el-col :span="12" :offset="4">
      <el-form :model="changeForm" label-width="110px" class="demo-formData">
        <el-form-item label="老师" >
          <el-input  :placeholder="currentArrange.teacher_name" disabled></el-input>
        </el-form-item>
		<el-form-item label="学生" >
          <el-input  :placeholder="currentArrange.student_name" disabled></el-input>
        </el-form-item>
         <el-form-item label="选择时间" style="white-space: nowrap;">
            <el-time-select placeholder="起始时间" v-model="changeForm.time_from" :picker-options="{
  							start: '07:00',
  							step: '00:15',
  							end: '23:45'
  							}">
            </el-time-select>
            <el-time-select placeholder="结束时间" v-model="changeForm.time_to" :picker-options="{
  							start: '07:00',
  							step: '00:15',
  							end: '23:45',
  							minTime: changeForm.time_from
  							}">
            </el-time-select>
          </el-form-item>
          <el-form-item label="选择日期">
             <el-date-picker
              v-model="changeForm.date"
              type="date"
              placeholder="选择开始日期"
              :picker-options="pickerOptions0">
    </el-date-picker>
         </el-form-item>
      </el-form>
	  	</el-col>
  		</el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogChangeVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeArrange()">确 定</el-button>
      </div>
    </el-dialog>
		
	</div>
</template>

<script>
import headTop from "../components/headTop";
import {
  getSortTeacherArrangeList,
  deleteSchedule,
  changeSchedule,
  searchUser
} from "@/api/getData";
import moment from "moment";
export default {
  data() {
    return {
      dialogDeleteConfirm: false,
      isBatchManage: false,
      multipleSelection: [],
      filterUser: "",
      filterUserId: 0,
      timeType: "未来排课",
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      dialogChangeVisible: false,
      changeLoading: false,
      changeForm: {},
      formLabelWidth: "120px",
      tableData: [],
      currentPage: 1,
      count: 30,
      orderKey: 0,
      currentArrange: {},
      startDate: "",
      endDate: "",
      timeArrange: []
    };
  },
  mounted() {},
  created() {
    this.$bus.on("refresh-arrange", this.refreshInfo);
  },
  beforeDestroy() {
    this.$bus.off("refresh-arrange", () => console.log("unregister"));
  },
  methods: {
    batchManage() {
      this.isBatchManage = !this.isBatchManage;
    },
    deleteSelectedArrange() {
      this.dialogDeleteConfirm = true;
    },
    deleteArrange() {
      let ids = [];
      if (this.multipleSelection) {
        this.multipleSelection.forEach(item => {
          ids.push(item.id);
        });
      }
      this.deleteOrderedSchedule(ids);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // console.log(this.multipleSelection);
    },
    removeFilter() {
      this.filterUser = "";
      this.filterUserId = 0;
      this.getSortList();
    },
    async querySearchAsync(queryString, cb) {
      if (queryString) {
        try {
          const res = await searchUser("", {
            keyword: queryString
          });
          if (res.resCode == 0) {
            res.data.forEach(item => {
              item.value = item.username;
            });
            cb(res.data);
          }
        } catch (err) {
          console.log(err);
        }
      }
    },
    addressSelect(user) {
      this.filterUser = user.username;
      this.filterUserId = user.id;
      this.getSortList();
    },
    searchByTimeArrange() {
      this.startDate = moment(this.timeArrange[0]).format("YYYY-MM-DD");
      this.endDate = moment(this.timeArrange[1]).format("YYYY-MM-DD");
      this.timeType = "";
      this.getSortList();
    },
    onTypeChange(label) {
      this.getSortList();
    },
    refreshInfo() {
      this.getSortList();
    },
    changeArrange() {
      this.$confirm("是否确认修改排课信息?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.updateArrange();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消修改"
          });
        });
    },
    formatter(row, column) {
      return row.address;
    },
    handleClick(row) {
      this.dialogChangeVisible = true;
      this.currentArrange = row;
    },
    handleDeleteClick(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let ids = [];
          ids.push(row.id);
          this.deleteOrderedSchedule(ids);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async updateArrange() {
      this.changeLoading = true;
      this.changeForm.teacher_id = this.currentArrange.teacher_id;
      this.changeForm.student_id = this.currentArrange.student_id;
      this.changeForm.id = this.currentArrange.id;
      this.changeForm.date = moment(this.changeForm.date).format("YYYY-MM-DD");
      //todo 修改排期
      const res = await changeSchedule(this.changeForm);
      this.changeLoading = false;
      if (res.resCode == 0) {
        this.dialogChangeVisible = false;
        this.$message({
          type: "success",
          message: "修改成功"
        });
        this.getSortList();
      } else {
        this.$message.error(res.resMsg);
      }
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getSortList();
    },
    handleSizeChange(val) {},
    sortChange({ column, prop, order }) {
      switch (prop) {
        case "date":
          this.orderKey = 0;
          break;
        case "teacher_name":
          this.orderKey = 2;
          break;
        case "student_name":
          this.orderKey = 4;
          break;
        case "status_str":
          this.orderKey = 6;
          break;
      }
      if (order == "ascending") {
        this.orderKey += 1;
      }
      this.getSortList();
    },
    async deleteOrderedSchedule(ids) {
      let data = {};
      data.ordered_schedule_ids = ids;
      const res = await deleteSchedule(data);
      if (res.resCode == 0) {
        this.dialogDeleteConfirm = false;
        this.$message({
          type: "success",
          message: "删除成功!"
        });
        this.getSortList();
      }
    },
    async getSortList() {
      if (this.timeType == "未来排课") {
        this.startDate = moment().format("YYYY-MM-DD");
        this.endDate = "";
      } else if (this.timeType == "过往排课") {
        this.startDate = "";
        this.endDate = moment().format("YYYY-MM-DD");
      }
      const res = await getSortTeacherArrangeList(
        this.currentPage,
        this.orderKey,
        this.startDate,
        this.endDate,
        this.filterUserId
      );
      if (res.resCode == 0) {
        res.data.data.forEach(item => {
          if (item.status == 0) {
            item.status_str = "正常";
          } else if (item.status == 1) {
            item.status_str = "请假中";
          } else if (item.status == 2) {
            item.status_str = "被拒绝";
          } else {
            item.status_str = "";
          }

          if (item.clocked == 0) {
            item.clocked_str = "否";
          } else {
            item.clocked_str = "是";
          }
        });
        // console.log(res.data.data);
        this.tableData = res.data.data;
        this.count = res.data.count;
        this.currentPage = res.data.page;
      }
    }
  },
  components: {
    headTop
  }
};
</script>

<style lang="less">
@import "../style/mixin";
.table_container {
  margin-top: 20px;
  width: 90%;
  margin-left: auto;
  margin-right: auto;
}
</style>
